<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ruby lexical structure</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Ruby, learn Ruby, lexical structure, programming, language">
<meta name="description" content="In this part of the Ruby tutorial, we cover Ruby lexical structure.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Ruby lexical structure</h1>

<p>
Computer languages, like human languages, have a lexical structure. A source 
code of a Ruby program consists of tokens. Tokens are atomic code elements. 
In Ruby language we have various lexical structures, such as comments, variables, 
literals, white spaces, operators, delimiters and keywords.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<h2>Comments</h2>

<p>
<b>Comments</b> are used by humans to clarify the source code. 
There are two types of comments in Ruby. Single-line and multi-line
comments. Single-line comments begin with the # character.  
Multi-line comments are put between the =begin and =end tokens.
</p>

<pre class="code">
#!/usr/bin/ruby

=begin
  comments.rb
  author Jan Bodnar
  ZetCode 2011
=end

# prints message to the terminal
puts "Comments example"
</pre>

<p>
An example showing both types of comments. Comments are ignored by
the Ruby interpreter.
</p>

<pre class="explanation">
=begin
  comments.rb
  author Jan Bodnar
  ZetCode 2011
=end
</pre>

<p>
This is an example of a multi-line comment. The two tokens must start at
the beginning of the line. 
</p>

<h2>White space</h2> 
 
<p> 
White space in Ruby is used to separate tokens and terminate statements
in the source file. It is also used to improve readability of the source code. 
</p> 
 
<pre>
if true then
    puts "A message"
end
</pre> 
 
<p> 
White spaces are required in some places. For example between the <code>if</code> 
keyword and the <code>true</code> keyword. Or between the <code>puts</code> method
and the actual string. In other places, it is forbidden. It cannot be present in
variable identifiers or language keywords.
</p> 
 
<pre>
a=1
b = 2
c  =  3
</pre> 
 
<p> 
The amount of space put between tokens is irrelevant for the Ruby interpreter.
However, it is important to have one style throughout the project.  
</p> 

<hr class="btm">

<pre class="code">
#!/usr/bin/ruby

x = 5 + 3
puts x

x = 5 
      + 3
puts x      

x = 5 + 
        3
puts x
</pre>

<p>
A new line, a form of a white space, can be used to terminate statements. 
</p>

<pre class="explanation">
x = 5 + 3
</pre>

<p>
In the first case, we have one statement. The sum of the addition is
assigned to the x variable. The variable holds 8. 
</p>

<pre class="explanation">
x = 5 
      + 3
</pre>

<p>
Now, there are two statements. The first statement is terminated with a 
newline. The x variable is 5. There is another statement, +3, which has no
effect. 
</p>

<pre class="explanation">
x = 5 + 
        3
</pre>

<p>
Finally, we have one statement. The newline is preceded with a + binary operator, so
the interpreter expects another value. It looks on the second line. In this case,
it takes both lines as one statement. The x variable is 8. 
</p>

<pre>
$ ./whitespace.rb
8
5
8
</pre>

<p>
Output.
</p>


<h2>Variables</h2>

<p>
A <b>variable</b> is an identifier, which holds a value. In 
programming we say, that we assign a value to a variable. Technically speaking, 
a variable is a reference to a computer memory, where the value is stored. 
In Ruby, a variable can hold a string, a number or various objects.
Variables can be assigned different values over time. 
</p>

<p>
Variable names in Ruby are created from alfanumeric characters and underscore (_) character. 
A variable cannot begin with a number. The interpreter can easier distinguish 
between a literal number and a variable. Variable names cannot begin with a capital letter. 
If an identifier begins with a capital letter, it is considered to be a constant in Ruby.
</p>

<pre>
Value
value2
company_name
</pre>

<p>
These are valid variable names. 
</p>

<pre>
12Val
exx$
first-name
</pre>

<p>
These are examples of invalid variable names. 
</p>

<p>
Variable names may be preceded by two special characters, $ and @. They are used
to create a specific variable scope. 
</p>


<p>
The variables are <b>case sensitive</b>. This means, that  <code>price</code>, 
and <code>pRice</code> are two different identifiers. 
</p>

<pre class="code">
#!/usr/bin/ruby

number = 10
numBER = 11

puts number, numBER
</pre>

<p>
In our script, we assign two numeric values to two identifiers. 
number and numBER are two different variables. 
</p>

<pre>
$ ./case.rb
10
11
</pre>

<p>
This is the output of the script. 
</p>

<h2>Constants</h2>

<p>
Constants are value holders, which hold only one value over time.
An identifier with a first uppercase letter is a constant in Ruby.
In programming it is a convention to write all characters of a constant
in uppercase. 
</p>

<p>
Unlike in other languages, Ruby does not enforce constants to have only
one value over time. The interpreter only issues a warning if we assign
a new value to an existing constant. 
</p>


<pre class="code">
#!/usr/bin/ruby

Name = "Robert"
AGE = 23

Name = "Juliet"
</pre>

<p>
In the above example, we create two constants. One of the constants is redefined
later. 
</p>

<pre class="explanation">
Name = "Robert"
AGE = 23
</pre>

<p>
Two constants are created. When the identifier's name begins with an uppercase 
letter, than we have a constant in Ruby. By convention, constants are usually written
in upperacse letters. 
</p>

<pre class="explanation">
Name = "Juliet"
</pre>

<p>
We redefine a constant. Which issues a warning. 
</p>

<pre>
$ ./constants.rb
./constants.rb:6: warning: already initialized constant Name
</pre>

<p>
Running the example.
</p>

<h2>A literal</h2>

<p>
A literal is a textual representation of a particular value of a type. 
Literal types include boolean, integer, floating point, string, character, 
and date. Technically, a literal will be assigned a value at compile 
time, while a variable will be assigned at runtime.
</p>

<pre>
age = 29
nationality = "Hungarian"
</pre>

<p>
Here we assign two literals to variables. Number 29 and 
string "Hungarian" are literals. 
</p>

<pre class="code">
#!/usr/bin/ruby

require 'date'

sng = true
name = "James"
job = nil
weight = 68.5
born = Date.parse("November 12, 1986")

puts "His name is #{name}"

if sng == true
    puts "He is single"
else
    puts "He is in a relationship"
end

puts "His job is #{job}"
puts "He weighs #{weight} kilograms"
puts "He was born in #{born}"
</pre>

<p>
In the above example, we have multiple literals. 
The bool literal may have value true or false. 
James is a string literal. The nil is an absense of a value.
68.5 is a floating point literal. 
Finally, the November 12, 1987 is a date literal.
</p>

<pre>
$ ./literals.rb
His name is James
He is single
His job is 
He weighs 68.5 kilograms
He was born in 1986-11-12
</pre>

<p>
This is the output of the literals.rb script. 
</p>


<h2>Blocks</h2>

<p>
Ruby statements are often organized into blocks of code. A code block
can be delimited using { } characters or <code>do</code>, <code>end</code>
keywords.  
</p>

<pre class="code">
#!/usr/bin/ruby

puts [2, -1, -4, 0].delete_if { |x| x &lt; 0 }
    
[1, 2, 3].each do |e|
    puts e
end
</pre>

<p>
In the example, we show two code blocks. 
</p>

<p>
Flow control of Ruby code is often done with the <code>if</code> keyword.
The keyword is followed by a block of code. In this case a block of code
is delimited by <code>then</code>, <code>end</code> keywords, where
the first keyword is optional. 
</p>

<pre class="code">
#!/usr/bin/ruby

if true then
    puts "Ruby language"
    puts "Ruby script"
end
</pre>

<p>
In the above example, we have a simple block of code. It has two 
statements. The block is delimited by <code>then</code>, <code>end</code>
keywords. The <code>then</code> keyword can be omitted.
</p>


<h2>Sigils</h2>

<p>
Sigils $, @ are special characters that denote a scope in a variable. 
The $ is used for global variables, @ for instance variables and @@ for
class variables. 
</p>

<pre>
$car_name = "Peugeot"
@sea_name = "Black sea"
@@species = "Cat"
</pre>

<p>
Sigils are always placed at the beginning of the variable identifier.
</p>

<h2>Operators</h2>

<p>
An <b>operator</b> is a symbol used to perform an 
action on some value. (answers.com) 
</p>

<pre>
!    +    -    ~    *    **    /    %
&lt;&lt;    >>    &amp;    |    ^
==    ===    !=    &lt;=>    >=    >
&lt;    &lt;=    =    %=    /=    -=
+=    *=    **=    ..    ...    not
and    or    ?:    &amp;&amp;    || 
</pre>

<p>
This is a list of operators available in Ruby language. We will talk 
about operators later in the tutorial.
</p>

<h2>Delimiters</h2>

<p>
A <b>delimiter</b> is a sequence of one or more characters 
used to specify the boundary between separate, independent regions in plain 
text or other data stream. (wikipedia)
</p>

<pre>
(       )       [       ]       {       }      
,       ;       '       "       |       |
</pre>

<pre class="code">
#!/usr/bin/ruby

name = "Jane"
occupation = 'Student'
numbers = [ 2, 3, 5, 3, 6, 2 ]

puts name; puts occupation
puts numbers[2]
numbers.each { |i| puts i }
puts ( 2 + 3 ) * 5
</pre>

<p>
In the above example, we show the usage of various Ruby delimiters.
</p>

<pre class="explanation">
name = "Jane"
occupation = 'Student'
</pre>

<p>
Single and double quotes are used to delimit a string in Ruby. 
</p>

<pre class="explanation">
numbers = [ 2, 3, 5, 3, 6, 2 ]
</pre>

<p>
The square brackets are used to set boundaries for an array. 
The commas are used to separate items in the array.
</p>

<pre class="explanation">
puts name; puts occupation
</pre>

<p>
The semicolon is used in Ruby to separate two statements in a Ruby
source code. 
</p>

<pre class="explanation">
puts numbers[2]
</pre>

<p>
Delimiters can be used in different contexts. Here the square brackets 
are used to access an item in the array.
</p>

<pre class="explanation">
numbers.each { |i| puts i }
</pre>

<p>
Curly brackets are used to define a block of code. Pipes are used
to define an element, which is filled with a current array item
for each loop cycle. 
</p>

<pre class="explanation">
puts ( 2 + 3 ) * 5
</pre>

<p>
Parentheses can be used to alter the evaluation of an expression.
</p>

<h2>Keywords</h2>

<p>
A keyword is a reserved word in the Ruby programming language. Keywords 
are used to perform a specific task in the computer program. For example, 
print a value to the console, do repetitive tasks or perform logical operations. 
A programmer cannot use a keyword as an ordinary variable. 
</p>

<pre>
alias    and      BEGIN      begin    break    case
class    def      defined?   do       else     elsif
END      end      ensure     false    for      if
in       module   next       nil      not      or
redo     rescue   retry      return   self     super
then     true     undef      unless   until    when 
while    yield 
</pre>

<p>
This is a list of Ruby keywords. 
</p>

<p>
This was the Ruby lexical structure. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified June 10, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

